package com.liar.testwallet;

import android.content.Context;
import android.os.Build;

import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;

import androidx.annotation.RequiresApi;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;

public class FileSecurity {
    private static final String KEY_ALIAS = "fileEncryptionKey";
    private static final String KEYSTORE_TYPE = "AndroidKeyStore";

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void encryptFileAndSave(Context context, String inputFile, String outputFile) throws Exception {
        // 生成AES密钥
        SecretKey secretKey = generateAESKey();

        // 加密文件
        byte[] encryptedData = encryptFile(inputFile, secretKey);

        // 保存加密文件
        saveEncryptedFile(outputFile, encryptedData);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private SecretKey generateAESKey() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, InvalidAlgorithmParameterException {
        KeyGenerator keyGen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE_TYPE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            keyGen.init(new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                    .build());
        }
        return keyGen.generateKey();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private byte[] encryptFile(String inputFile, SecretKey key) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] fileBytes = Files.readAllBytes(Paths.get(inputFile));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(fileBytes);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void saveEncryptedFile(String outputFile, byte[] encryptedData) throws IOException {
        Files.write(Paths.get(outputFile), encryptedData);
    }
}

